'use strict';
/*
 * passport-ttxs
 */

var util = require('util');
var passport = require('passport-strategy');
const User = require('../models/user');
const md5 = require('MD5');

/**
 * [TTSXStrategy description] 登录策略
 * @param {Object} options.authorizationURL 登录url
 * @param {Function} verify 回调函数
 *
 */
function TTSXStrategy(options, verify) {
    options = options || {};

    if(!verify) {
        throw new TypeError('TTSXStrategy required a verify callback');
    }

    if(typeof verify !== 'function') {
        throw new TypeError('_verify must be function');
    }

    options = options || {};
    this.name = 'login';
    this._verify = verify;
    this._authorizationURL = options.authorizationURL;
    this._host = options.host;

    passport.Strategy.call(this, options, verify);
}

/**
 * Inherit from 'passort.Strategy'
 */
util.inherits(TTSXStrategy, passport.Strategy);


TTSXStrategy.prototype.authenticate = function(req) {
    var self = this;
    function verified(err, user, info) {
        if(err) {
            return self.error(err);
        }
        if(!user) {
            if(typeof info === 'string') {
                info = {
                    message: info
                };
            }
            info = info || {};
            return self.fail(400);
        }
        self.success(user, info);
    }
    const loginInfo = req.body;

    User.where({
        account: loginInfo.account,
        pwd: md5(loginInfo.pwd)
    })
    .fetch()
    .then(user => {
        // format data
        if(self._passReqToCallback) {
            self._verify(req, user, verified);
        }
        else {
            self._verify(user, verified);
        }
    })
};

/**
 * Expose `Strategy`.
 */
module.exports = TTSXStrategy;
